package com.ligg.controller;

import com.ligg.pojo.Result;
import com.ligg.pojo.User;
import com.ligg.service.UserService;
import com.ligg.utils.Md5Util;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    UserService userService;
    // 注册
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "[a-z A-Z0-9]{5,15}") String username,
                           @Pattern(regexp = "[a-z A-Z0-9]{5,15}")String password){
        //查询用户
        User user = userService.findByUsername(username);
        if (user == null){
            //用户名为空，注册用户.
            userService.register(username, password);
            return Result.success();
        }else {
            //用户名不为空,返回提示信息.
            return Result.error("用户名已存在");
        }
    }

    //登录
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "[a-z A-Z0-9]{5,15}") String username,
                        @Pattern(regexp = "[a-z A-Z0-9]{5,15}")String password){
        //1、判断用户是否存在
        User loginUser = userService.findByUsername(username);
        if (loginUser == null){
            return Result.error("用户不在");
        }
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())){
        //2、登录认证
        return Result.success("jwt token令牌...");
        }
        return Result.error("密码错误");
    }
}
